package com.graph;

import java.util.*;
import java.util.logging.Handler;

public class Solution1061 {
    int[] father;

    public String smallestEquivalentString(String s1, String s2, String baseStr) {
        father = new int[26];
        for (int i = 0; i < 26; i++) {
            father[i] = i;
        }
        for (int i = 0; i < s1.length(); i++) {
            join(s1.charAt(i) - 'a', s2.charAt(i) - 'a');
        }
        HashMap<Integer, List<Character>> map = new HashMap<>();
        for (int i = 0; i < 26; i++) {
            int root = find(i);
            List<Character> characterList = map.getOrDefault(root, new ArrayList<>());
            characterList.add((char) ('a' + i));
            map.put(root, characterList);
        }
        for (Map.Entry<Integer, List<Character>> entry : map.entrySet()) {
            Collections.sort(entry.getValue());
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < baseStr.length(); i++) {
            char c = baseStr.charAt(i);
            int cur = c - 'a';
            cur = find(cur);
            sb.append(map.get(cur).get(0));
        }
        return sb.toString();
    }

    public int find(int x) {
        if (x == father[x]) return x;
        father[x] = find(father[x]);
        return father[x];
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
    }
}
